<template>
  <div class="container">
    <div class="header">
      <h1>记账软件</h1>
    </div>
    <div class="totalcome clearfix">
      <div class="income leftfix clearfix">
        <div class="left leftfix">
          <div class="top leftfix">
            <el-date-picker class="pick leftfix" v-model="value1" type="year" placeholder="选择年份" />
          </div>
          <div class="buttom leftfix">
            <div class="leftfix hanzi">年度收入：</div>
          </div>
        </div>
        <div class="right rightfix">
          <div class="circle-container">
            <div class="circle">
              <span class="number1">{{ income }}元</span>
            </div>
          </div>
        </div>
      </div>

      <div class="outcome rightfix">
        <div class="left leftfix">
          <div class="top leftfix">
            <el-date-picker class="pick leftfix" v-model="value2" type="year" placeholder="选择年份" />
          </div>
          <div class="buttom leftfix">
            <div class="leftfix hanzi">年度支出：</div>
          </div>
        </div>

        <div class="right rightfix">
          <div class="circle-container">
            <div class="circle">
              <span class="number2">{{ outcome }}元</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="show">
      <div class="condition">
        类别：
        <el-select v-model="value3" placeholder="Select" style="width: 240px">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <span class="demonstration">时间：</span>
        <el-date-picker v-model="value4" type="daterange" unlink-panels range-separator="To"
          start-placeholder="Start date" end-placeholder="End date" @change="handleDateChange" />
        <el-button type="primary" :icon="Plus" @click="openDialog">新增</el-button>
        <el-button type="primary" :icon="Search" @click="search">查询</el-button>
      </div>
      <div class="table">
        <el-table :data="tableData.values" stripe style="width: 100%">
          <el-table-column prop="id" label="编号" width="180" />
          <el-table-column prop="amount" label="金额" width="180" />
          <el-table-column prop="date" label="日期" />
          <el-table-column prop="category" label="收入/支出" />
          <el-table-column prop="reason" label="原因" />
        </el-table>
      </div>
      <div class="fenye">
        <el-pagination background layout="prev, pager, next,total" :total=total @current-change="handlePageChange"
          :current-page="currentPage" />

      </div>

    </div>
  </div>

  <div>

    <!-- 弹窗 -->
    <el-dialog v-model="isDialogVisible" title="新增记录" width="30%" :before-close="handleClose">
      <!-- 表单内容 -->
      <el-form :model="form" label-width="auto" style="max-width: 600px">
        <el-form-item label="金额">
          <el-input v-model="form.amount" />
        </el-form-item>
        <el-form-item label="类别">
          <el-select v-model="form.category" placeholder="收入/支出">
            <el-option label="收入" value="收入" />
            <el-option label="支出" value="支出" />
          </el-select>
        </el-form-item>
        <el-form-item label="选择时间">
          <el-col :span="11">
            <el-date-picker v-model="form.date1" type="date" placeholder="Pick a date" style="width: 100%" />
          </el-col>
        </el-form-item>
        <el-form-item label="原因">
          <el-input v-model="form.reason" type="原因" />
        </el-form-item>
      </el-form>

      <!-- 弹窗底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus';
import { Search, Plus } from '@element-plus/icons-vue'
const currentPage = ref(1); // 当前页码
const handlePageChange = (page: number) => {
  currentPage.value = page; // 更新当前页码
  search(); // 获取对应页码的数据
};
let total = 0
// 控制弹窗显示状态
const isDialogVisible = ref(false);
const form = ref({
  amount: 0,
  category: '',
  date1: '',
  reason: '',
})
// 打开弹窗
const openDialog = () => {
  isDialogVisible.value = true;
};
// 关闭弹窗
const closeDialog = () => {
  isDialogVisible.value = false;
};

// 弹窗关闭前的回调
const handleClose = (done: () => void) => {
  // 可以在这里添加一些关闭前的逻辑，比如提示用户保存数据
  closeDialog();
  done();
};
function resetForm() {
  form.value = {
    amount: 0,
    category: '',
    date1: '',
    reason: '',
  };
};
// 提交表单
async function onSubmit() {
  try {
    const params = {
      amount: Number(form.value.amount),
      date: dayjs(form.value.date1).format('YYYY-MM-DD'),
      category: form.value.category,
      reason: form.value.reason
    }
    let result = await axios.post('http://localhost:8088/account', params)

    if (result.status = 200) {
      ElMessage({
        message: '添加记录成功！',
        type: 'success', // 类型：success/warning/info/error
        duration: 2000, // 自动消失的时间（毫秒）
      });
    }
    closeDialog()
    // 重置表单
    resetForm()
  } catch (error) {
    alert(error)
  }
}

const value1 = ref(new Date());
const income = ref(0)
const selectedYear1 = computed(() => {
  return value1.value ? value1.value.getFullYear() : '';
});
async function GetInCome() {
  try {
    const params = {
      date: selectedYear1.value
    }
    let result = await axios.get('http://localhost:8088/income', { params })
    income.value = result.data
    // console.log(income.value);
  } catch (error) {
    alert(error)
  }
}
watch(value1, (newDate) => {
  if (newDate) {
    GetInCome();
  }
});
onMounted(() => {
  GetInCome();
  GetOutCome();
  search();
});

const value2 = ref(new Date());
const outcome = ref(0)
const selectedYear2 = computed(() => {
  return value2.value ? value2.value.getFullYear() : '';
});
async function GetOutCome() {
  try {
    const params = {
      date: selectedYear2.value
    }
    let result = await axios.get('http://localhost:8088/outcome', { params })
    outcome.value = result.data

  } catch (error) {
    alert(error)
  }
}
watch(value2, (newDate) => {
  if (newDate) {
    GetOutCome();
  }
});


const value3 = ref('')
const options = [
  {
    value: '收入',
    label: '收入',
  },
  {
    value: '支出',
    label: '支出',
  },
]
import dayjs from 'dayjs';
import { pa } from 'element-plus/es/locale/index.mjs';
const value4 = ref<[Date, Date] | []>([]);
// 使用 ref 来存储 startDate 和 endDate
const startDate = ref<Date | null>(null);
const endDate = ref<Date | null>(null);
//  处理日期范围变化的函数
const handleDateChange = (range: [Date, Date] | []) => {
  if (range.length === 2) {
    // 更新 startDate 和 endDate
    startDate.value = range[0];
    endDate.value = range[1];
  } else {
    // 如果用户清空选择，重置 startDate 和 endDate
    startDate.value = null;
    endDate.value = null;
  }
};


// 定义表格数据的类型
interface TableItem {
  id: number;
  amount: number;
  date: string;
  category: string;
  reason: string;
}

const tableData = ref<{ values: TableItem[] }>({
  values: [], // 初始化为空数组
});
async function search() {
  try {
    if (startDate.value == null && endDate.value == null && value3.value == '') {
      const params = {
        page: currentPage.value,
      }
      let result = await axios.get('http://localhost:8088/accounts', { params })
      tableData.value.values = result.data.data
      total = result.data.total
    } else if (startDate.value == null && endDate.value == null) {
      const params = {
        page: currentPage.value,
        category: value3.value,
      }
      let result = await axios.get('http://localhost:8088/accounts', { params })
      tableData.value.values = result.data.data
      total = result.data.total
    } else if (value3.value == '') {
      const params = {
        page: currentPage.value,
        startDate: dayjs(startDate.value).format('YYYY-MM-DD'),
        endDate: dayjs(endDate.value).format('YYYY-MM-DD')
      }
      let result = await axios.get('http://localhost:8088/accounts', { params })
      tableData.value.values = result.data.data
      total = result.data.total
    } else {
      const params = {
        page: currentPage.value,
        category: value3.value,
        startDate: dayjs(startDate.value).format('YYYY-MM-DD'),
        endDate: dayjs(endDate.value).format('YYYY-MM-DD')
      }
      let result = await axios.get('http://localhost:8088/accounts', { params })
      tableData.value.values = result.data.data
      total = result.data.total
    }
  } catch (error) {
    alert(error)
  }
}


</script>
<style>
/* 清除所有元素的默认样式 */
* {
  margin: 0;
  padding: 0;
}

/* 设置左浮动 */
.leftfix {
  float: left;
}

/* 设置右浮动 */
.rightfix {
  float: right;
}

/* 清除浮动的影响 */
.clearfix::after {
  content: '';
  display: block;
  clear: both;
}

.container {
  /* 设置最外面大容器的宽度 */
  width: 1024px;
  /* height: 200px;
    background-color: gray; */
  /* 设置最外面大容器水平居中，高度由内容撑开 */
  margin: auto;
  /* 设置所有文字水平居中 */
  text-align: center;
}

.top {

  height: 55px;
  width: 230px;

}

.buttom {

  height: 55px;
  width: 230px;

}

.header {
  background-color: #ccc;
  color: green;

}

.income,
.outcome {
  border: 1px black solid;
  height: 120px;
  width: 500px;
  line-height: 100px;
}

.left {

  width: 250px;
  height: 118px;

}

.right {
  /* border: 1px red solid; */
  height: 116px;
  width: 200px;
  margin-top: 0px;

}

.income {
  margin-right: 20px;
  background-color: skyblue;
}

.outcome {
  background-color: rgb(12, 209, 209);
}

.hanzi {
  width: 200px;
  height: 40px;
  font-size: 30px;
  margin-top: 10px;
  margin-left: 5px;
  line-height: 40px;
}

.totalcome {
  margin-top: 10px;
}

.select {
  width: 220px;
  height: 30px;
  line-height: 10px;
  margin-top: 10px;
  margin-left: 0px;
  /* border: 1px black solid; */

}

.pick {
  margin-top: 10px;
  margin-left: 5px;
}

.circle-container {
  /* display: flex;
  justify-content: center;
  align-items: center; */
  height: 200px;

  /* margin-left: 300px; */
  margin-top: 0px;
}

.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #3498db;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 5px solid #2980b9;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}


.number1,
.number2 {
  font-size: 24px;
  font-weight: bold;
  color: white;
}

.number1 {
  color: green;
}

.number2 {
  color: red;
}

.show {
  margin-top: 10px;
}

.fenye {

  display: flex;
  justify-content: center;
}
</style>
